const { post, get, put } = require('../utils/request')

/**
 * 获取商品列表（分页）
 * @param {Object} params 查询参数
 */
function getProductList(params = {}) {
  const { storeManagerId, page = 1, size = 10, keyword = '' } = params

  // 构建请求参数，过滤掉null和undefined值
  const requestParams = {
    pageNum: page,
    pageSize: size,
    keyword
  }

  // 只有当storeManagerId有效时才添加到参数中
  if (storeManagerId !== null && storeManagerId !== undefined) {
    requestParams.storeManagerId = storeManagerId
  }

  return get('/store-product/online', requestParams)
}

/**
 * 获取热门商品（用于首页轮播图）
 * @param {Number} size 获取数量，默认4个
 */
function getHotProducts(size = 4) {
  return get('/store-product/online', {
    pageNum: 1,
    pageSize: size
  })
}

/**
 * 获取商品详情
 * @param {Number} id 商品ID
 */
function getProductDetail(id) {
  return get(`/store-product/public/${id}`)
}

/**
 * 购买商品
 * @param {Object} data 购买数据
 */
function purchaseProduct(data) {
  return post('/purchase/buy', data)
}

/**
 * 获取我的购买记录
 * @param {Object} params 查询参数
 */
function getMyPurchaseRecords(params = {}) {
  const { page = 1, size = 10, keyword = '' } = params
  
  // 构建请求参数
  const requestParams = {
    page,
    size
  }
  
  // 只有当keyword有值时才添加到参数中
  if (keyword && keyword.trim() !== '') {
    requestParams.keyword = keyword.trim()
  }
  
  return get('/purchase/my-records/page', requestParams)
}

/**
 * 获取购买记录详情
 * @param {Number} id 购买记录ID
 */
function getPurchaseRecordDetail(id) {
  return get(`/purchase/${id}`)
}

/**
 * 取消购买记录
 * @param {Number} id 购买记录ID
 */
function cancelPurchaseRecord(id) {
  return put(`/purchase/cancel/${id}`)
}

module.exports = {
  getProductList,
  getHotProducts,
  getProductDetail,
  purchaseProduct,
  getMyPurchaseRecords,
  getPurchaseRecordDetail,
  cancelPurchaseRecord
}